package com.guchenbo.example.pdf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import static org.eclipse.jdt.internal.compiler.parser.Parser.name;
//import static org.hsqldb.HsqlDateTime.e;

/**
 * @Author guchenbo
 * @Date 2018/6/6.
 */
public class PdfTest {

    /**
     * @author hsm
     */
    private static String PDFPATH = "/Users/guchenbo/Downloads/PRR Tahap 2a Bojong.pdf";
    private static String FILEPATH = "D:/Maven权威指南中文版.doc";

    public static Pattern pattern2 = Pattern.compile("[\\d]{2}-[\\d]{2}-[\\d]{4}");

    public static void main(String[] args) throws Exception {
        //        File file2 = new File(PDFPATH);
        //        String content = getPdfContent(file2);
        //        System.out.println(content);
        //        toFile(content, FILEPATH);

        File file = new File("/Users/guchenbo/tongdun/海外爬虫项目/印尼/ktp/ktppdf");
        int i = 0;
        List<KtpResult> list = new ArrayList<>();
        for (File f : file.listFiles((dir, name) -> name.startsWith("PRR Tahap 2a "))) {
            System.out.println(f.getName());
            //            f.renameTo(new File(file, "DAFTAR KTP YANG SUDAH DICETAK UPDATE-" + (++i) + ".pdf"));

            list.addAll(parseFile2a(f));
//                        break;
        }
        System.out.println(list.size());
        System.out.println(JSON.toJSON(list));
    }

    public static List<KtpResult> parseFile2a(File file) {
        String content = null;
        List<KtpResult> list = new ArrayList<>();
        try {
            content = getPdfContent(file);
            System.out.println(content);

            List<String> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();

            String[] cs = content.split("\n");
            if (cs.length == 227) {
                System.out.println("dd");
            }

            int k = 0;
            for (int j = 0; j < cs.length; j++) {
                String c = cs[j].trim();
                if (c.equals("KRISTENPRINT_READY_RECORD")) {
                    c = "KRISTEN PRINT_READY_RECORD";
                }
                if (c.equals("KATHOLIKPRINT_READY_RECORD")) {
                    c = "KATHOLIK PRINT_READY_RECORD";
                }

                String[] cs2 = c.split(" ");
                if (cs2.length == 2 || cs2.length == 3) {
                    if (c.contains("_") && !c.contains("CURRENT_STATUS_CODE")) {
                        list2.add(c);

                        if (k != j - 1) {
                            System.out.println("k ->" + k + " -> " + cs[k + 1]);
                        }
                        k = j;
                    } else {

                    }

                } else {
                    if (NumberUtils.isNumber(cs2[0])) {
                        list1.add(c);
                    }
                    //                    if (c.contains("READY_RECORD")) {
                    //                        System.out.println(c);
                    //                    }
                }
            }

            if (list1.size() != list2.size()) {
                System.out.println(list1.size());
            }

            for (int i = 0; i < list1.size(); i++) {
                String s1 = list1.get(i).trim();
                String s2 = list2.get(i).trim();

                String s = String.join(" ", s1, s2);
                String[] ss = s.split(" ");
                String cardNo = ss[1];
                String nokk = ss[2];

                s = StringUtils.substringAfter(s, nokk).trim();
                Matcher matcher = pattern2.matcher(s);
                if (matcher.find()) {
                    int start = matcher.start();
                    String s11 = s.substring(0, start);
                    String s12 = s.substring(start);

                    ss = s12.split(" ");


                    List<String> sss = ppp2a(ss);
                    if (sss.size() != 9) {
                        System.out.println(sss.size());
                    }
                    String status = sss.get(0);
                    String agama = sss.get(1);
                    String rw = sss.get(2);
                    String rt = sss.get(3);
                    String kel = sss.get(4);
                    String kec = sss.get(5);
                    String gender = sss.get(6);

                    ss = s11.split(" ");
                    int len = ss.length;
                    String tmplLhr = ss[len - 1];
                    String name = StringUtils.substringBefore(s11, tmplLhr).trim();

                    KtpResult ktpResult = new KtpResult();
                    ktpResult.setName(name.trim());
                    ktpResult.setCardNo(cardNo);
                    ktpResult.setKkNo(nokk);
                    ktpResult.setTmpt(tmplLhr);
                    ktpResult.setGender(gender);
                    ktpResult.setKec(kec);
                    ktpResult.setKel(kel);

                    ktpResult.setRt(rt);
                    ktpResult.setRw(rw);

                    ktpResult.setAgama(agama);
                    ktpResult.setStatus(status);

                    list.add(ktpResult);
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static List<String> ppp2a(String[] ss) {
        List<String> list = new ArrayList<>();
        int len = ss.length;
        int b = 0;
        for (int j = len-1; j > 0; j--) {
            String s = ss[j];
            if (StringUtils.isBlank(s)) {
                continue;
            } else {
                list.add(s);
                if (isDate(s)) {
                    b = j;
                }
            }
            if (b > 0 && j==b-1) {
                break;
            }
        }
        return list;
    }

    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    private static boolean isDate(String s) {
        try {
            simpleDateFormat.parse(s);
            return true;
        } catch (ParseException e1) {
//            e1.printStackTrace();
            return false;
        }
    }

    public static Pattern pattern = Pattern.compile("[\\d]{6}.*");

    public static List<KtpResult> parseFile(File file) {
        String content = null;
        List<KtpResult> list = new ArrayList<>();
        try {
            content = getPdfContent(file);
            System.out.println(content);

            String[] cs = content.split("\n");
            for (String c : cs) {
                Matcher matcher = pattern.matcher(c);
                if (matcher.find()) {
                    int s = matcher.start();
                    String f = c.substring(0, s);
                    String se = c.substring(s);

                    KtpResult ktpResult = new KtpResult();
                    String name = StringUtils.substringAfter(f, " ");
                    String[] ses = StringUtils.split(se, " ");
                    String cardNo = String.join("", ses[0], ses[1]);
                    String almat = ses[2];
                    String rt = ses[3];
                    String rw = ses[4];

                    ktpResult.setName(name.trim());
                    ktpResult.setCardNo(cardNo);
                    ktpResult.setRt(rt);
                    ktpResult.setRw(rw);
                    ktpResult.setAlmat(almat);
                    list.add(ktpResult);

                    System.out.println(f + " ---> " + se);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取pdf的内容<br/>
     *
     * @param pdfPath
     * @return
     * @throws Exception
     */
    private static String getPdfContent(File pdfFile) throws Exception {
        boolean sort = false;// 是否排序
        int startPage = 1;// 开始提取页数
        int endPage = Integer.MAX_VALUE;   // 结束提取页数
        String content = null;//暂时存放pdf内容

        InputStream input = null;
        PDDocument document = null;
        try {
            input = new FileInputStream(pdfFile);
            // 加载 pdf 文档
            PDFParser parser = new PDFParser(input);
            parser.parse();
            document = parser.getPDDocument();
            // 获取内容信息
            PDFTextStripper pts = new PDFTextStripper();
            pts.setSortByPosition(sort);
            endPage = document.getNumberOfPages();
            //            System.out.println("Total Page: " + endPage);
            pts.setStartPage(startPage);
            pts.setEndPage(endPage);
            try {
                content = pts.getText(document);
            } catch (Exception e) {
                throw e;
            }
            //            System.out.println("Get PDF Content ...");
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != input)
                input.close();
            if (null != document)
                document.close();
        }
        return content;
    }

    private static void toFile(String content, String filePath) {
        try {
            File f = new File(filePath);
            if (!f.exists()) {
                f.createNewFile();
            }
            System.out.println("Write PDF Content to txt file ...");
            BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class KtpResult {
        @JSONField(serialize = false)
        private Long id;
        @JSONField(name = "card_no")
        private String cardNo;
        private String name;
        private String phone;
        private String gender;

        private String rt;
        private String rw;
        private String kkNo;
        private String agama;
        private String almat;
        private String tmpt;
        private String kec;
        private String kel;
        private String status;

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getTmpt() {
            return tmpt;
        }

        public void setTmpt(String tmpt) {
            this.tmpt = tmpt;
        }

        public String getKec() {
            return kec;
        }

        public void setKec(String kec) {
            this.kec = kec;
        }

        public String getKel() {
            return kel;
        }

        public void setKel(String kel) {
            this.kel = kel;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getCardNo() {
            return cardNo;
        }

        public void setCardNo(String cardNo) {
            this.cardNo = cardNo;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public String getRt() {
            return rt;
        }

        public void setRt(String rt) {
            this.rt = rt;
        }

        public String getRw() {
            return rw;
        }

        public void setRw(String rw) {
            this.rw = rw;
        }

        public String getKkNo() {
            return kkNo;
        }

        public void setKkNo(String kkNo) {
            this.kkNo = kkNo;
        }

        public String getAgama() {
            return agama;
        }

        public void setAgama(String agama) {
            this.agama = agama;
        }

        public String getAlmat() {
            return almat;
        }

        public void setAlmat(String almat) {
            this.almat = almat;
        }
    }
}
